package com.dede.getmusic.module.download

import android.app.IntentService
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.dede.getmusic.R
import com.dede.getmusic.data.SongFileInfo
import com.lzy.okserver.OkDownload
import org.jetbrains.anko.toast
import java.io.File

/**
 * @author hsh
 * @date 2017/10/13 13:56.
 * @doc 文件下载服务
 */
class DownloadServer(name: String) : IntentService(name), IDownloadView {

    override fun context() = this

    constructor() : this("DownloadServer")

    private val presenter by lazy { DownloadPresenter(this) }

    override fun onHandleIntent(intent: Intent?) {
        val songFileInfo = intent?.getSerializableExtra("info") as SongFileInfo
        presenter.startDownload(songFileInfo)
    }

    override fun downloadFinish(songFileInfo: SongFileInfo, t: File) {
        presenter.addFileTag(songFileInfo, t)
    }

    override fun notify(id: Int, progress: Int, text: String) {
        manager.notify(id, createNotify(progress, text))
    }

    override fun cancel(id: Int) {
        manager.cancel(id)
    }

    override fun createNotify(progress: Int, text: String): Notification {
        val intent = Intent(this, DownloadServer.CancelBroadcastReceiver::class.java)
        intent.action = "cancel"
        val pendingIntent = PendingIntent.getBroadcast(this, 100, intent, 0)
        val action = Notification.Action.Builder(R.drawable.ic_file_download, "取消", pendingIntent)
                .build()

        return Notification.Builder(this)
                .setContentTitle("下载中")
                .setProgress(100, progress, false)
                .setContentText(text)
                .setShowWhen(false)
                .setAutoCancel(false)
                .setOngoing(false)
                .addAction(action)
                .setSmallIcon(R.drawable.ic_file_download)
                .build()
    }

    override fun showToast(msg: String) {
        toast(msg)
    }

    private val manager by lazy { this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager }


    class CancelBroadcastReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent?.action == "cancel")
                OkDownload.getInstance().getTask("download")?.remove(true)
        }
    }

}